<?php
namespace Common\Api;
/**
 * 微信通用类
 * Class CommonApi
 * @package Common\Api
 */
class CommonApi{
	/**
	 * 服务号、订阅号
	 * @return WechatAuthApi
	 */
	public static function wechatAuthInfo(){
		$_weixin_config = array(
			"APPID" 		=> 	"",
			"APPSECRET" 	=> 	"",
		);		
		$appid 		= $_weixin_config['APPID'];
		$appsecret	= $_weixin_config['APPSECRET'];
		
		$access_token = F('access_token_for_yjcc');
		if($access_token['expire_in'] < time()){
			$wechatAuth = new WechatAuthApi($appid, $appsecret);
			$access_token = $wechatAuth->getAccessToken();
			F('access_token_for_yjcc', array('access_token' => $access_token, 'expire_in' => time() + 7000));
			return $wechatAuth;
		}else{
			return new WechatAuthApi($appid, $appsecret, $access_token['access_token']);
		}
	}

	/**
	 * 企业微信自动，两种场景下new 微信操作类
	 * 根据配置参数（appid,appsecret）获取access_token
	 * @return WechatWorkAuthApi
	 */
	public static function wechatWorkAuthInfo(){
		$_weixin_config = array(
			"corpid" 		=> 	"wxc80b03985e6115a5",
			"corpsecret" 	=> 	"E8DRFefDMHG_I6Lls9te4U2BHqiTbx67WhLPzLUzT-E",
			"AgentId" 		=> 	"1000050",
		);
		
		$corpid 		= $_weixin_config['corpid'];
		$corpsecret 	= $_weixin_config['corpsecret'];
		$AgentId 		= $_weixin_config['AgentId'];

		$access_token = F('access_token_for_ycjj');
		//access_token 超时无效，重新创建access_token
		if($access_token['expire_in'] < time()){
			//创建没带access_token,
			$wechatWorkAuth = new WechatWorkAuthApi($corpid,$corpsecret,$AgentId);
			$access_token = $wechatWorkAuth->getAccessToken();
			F('access_token_for_ycjj', array('access_token' => $access_token, 'expire_in' => time() + 7000));
			return $wechatWorkAuth;
		}else{
			//access_token 在有效期内，
			return new WechatWorkAuthApi($corpid,$corpsecret,$AgentId, $access_token['access_token']);
		}
	}


	/**
	 * 导出Excel
	 * @param $data
	 * @param $filename
	 * @param bool|true $download
	 * @return string
	 */
	static function exportExcel($data, $filename, $download = true){
		$filename = '/Application/Runtime/Temp/' . $filename . '.csv';
		$str = "";
		foreach($data as $key => $value){
			$str .= implode(',', str_replace(array(",", "\n", "\r", "\r\n"), '，', $value)) . "\n";
		}
		$str = iconv('utf-8','gb2312',$str);
		file_put_contents($_SERVER['DOCUMENT_ROOT'] . $filename, $str);
		if($download){
			header('Location:' . $filename);
		}else{
			return $filename;
		}
	}
}